import 'package:cached_network_image/cached_network_image.dart';
/**
 * 直播推荐页
 * page推荐
 */
import 'package:flutter/material.dart';
import 'package:flutter_easyrefresh/easy_refresh.dart';
import 'package:flutter_swiper/flutter_swiper.dart';
import 'package:overlay_support/overlay_support.dart';
import 'package:provide/provide.dart';
import 'package:qgchat/bloc/blocProvider.dart';
import 'package:qgchat/bloc/live/nominate.dart';
import 'package:qgchat/common/action/index.dart';
import 'package:qgchat/common/global/global.dart';
import 'package:qgchat/http/apis/user.dart';
import 'package:qgchat/http/models/bannerModel.dart';
import 'package:qgchat/http/models/followModel.dart';
import 'package:qgchat/http/models/recommendModel.dart';
import 'package:qgchat/states/states_model/index.dart';
import 'package:qgchat/widgets/avatar.dart';
import 'package:qgchat/widgets/easyRefreshWidget.dart';
import 'package:qgchat/widgets/tipsDialog.dart';
import 'package:url_launcher/url_launcher.dart';

import '../../../common/global/global.dart';

class Nominate extends StatefulWidget {
  Nominate({Key key}) : super(key: key);

  @override
  _NominateState createState() => _NominateState();
}

class _NominateState extends State<Nominate>
    with AutomaticKeepAliveClientMixin {
  @override
  bool get wantKeepAlive => true;

  NominateBloc bloc = NominateBloc();

  @override
  Widget build(BuildContext context) {
    super.build(context);
    return BlocProvider<NominateBloc>(
      bloc: bloc,
      child: _NominateBuild(),
    );
  }
}

// 构建推荐页
class _NominateBuild extends StatelessWidget {
  const _NominateBuild({Key key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    NominateBloc bloc = BlocProvider.of<NominateBloc>(context);

    return EasyRefresh(
      header: EasyRefreshSetting.header,
      footer: EasyRefreshSetting.footer,
      onRefresh: () async {
        bloc.onRefresh();
      },
      onLoad: () async {
        bloc.onLoad();
      },
      child: ListView(
        children: <Widget>[
          _SwiperBuild(),
          Provide<UserState>(
            builder: (context, child, user) {
              if (user.info == null || user.info.memberType == 1) {
                return Container();
              }

              return Column(
                children: <Widget>[
                  titleHandle(
                    "我关注的",
                    btnName: "查看全部",
                    callback: () {
                      final user = Provide.value<UserState>(context);
                      final info = user.info;
                      final isLogin = info != null;
                      if (isLogin) {
                        goPage(context, '/attentionOrFans');
                      } else {
                        TipsDialog.login(
                          context,
                          () {
                            goPage(context, '/phoneLogin');
                          },
                        );
                      }
                    },
                  ),
                  _MyFollowBuild(),
                ],
              );
            },
          ),
          titleHandle("热门"),
          _HotBuild(),
        ],
      ),
    );
  }

  // 生成标题
  titleHandle(String title, {String btnName, Function callback}) {
    List<Widget> widgetList = [
      Text(
        title,
        style: TextStyle(
          color: col("303133"),
          fontSize: px(26),
          fontWeight: FontWeight.bold,
        ),
      ),
    ];

    if (btnName != null && btnName.isNotEmpty && callback != null) {
      widgetList.add(
        FlatButton(
          onPressed: callback,
          padding: EdgeInsets.symmetric(horizontal: px(30)),
          child: Text(
            btnName,
            style: TextStyle(
              color: col("909399"),
              fontSize: px(24),
            ),
          ),
        ),
      );
    }

    return Container(
      height: px(55),
      padding: EdgeInsets.only(left: px(30)),
      margin: EdgeInsets.only(top: px(30)),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: widgetList,
      ),
    );
  }
}

/// 轮播
class _SwiperBuild extends StatelessWidget {
  _SwiperBuild({Key key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    final NominateBloc bloc = BlocProvider.of<NominateBloc>(context);
    return Container(
      height: px(230),
      padding: EdgeInsets.only(
        top: px(20),
        left: px(30),
        right: px(30),
      ),
      child: ClipRRect(
        borderRadius: BorderRadius.circular(px(15)),
        child: Container(
          height: px(230),
          child: StreamBuilder(
            stream: bloc.outSwiperList,
            builder: (BuildContext context, AsyncSnapshot snapshot) {
              if (bloc.bannerlist.length > 0) {
                List list = bloc.bannerlist;
                return Swiper(
                  onTap: (int index) {
                    _bannerClick(context, list, index);
                  },
                  autoplay: true,
                  itemCount: list.length,
                  itemBuilder: (BuildContext context, int index) {
                    return Image.network(
                      "${list[index].adUrl}?imageView2/2/h/230",
                      fit: BoxFit.contain,
                    );
                  },
                  pagination: SwiperPagination(
                    builder: DotSwiperPaginationBuilder(
                      color: col("909399"),
                      activeColor: col("606266"),
                      size: px(14),
                      activeSize: px(14),
                    ),
                  ),
                );
              } else {
                return Container();
              }
            },
          ),
        ),
      ),
    );
  }

  // 轮播点击跳转
  _bannerClick(
    BuildContext context,
    List<BannerModel> list,
    int index,
  ) async {
    final user = Provide.value<UserState>(context);
    final info = user.info;
    final isLogin = info != null;
    if (!isLogin) {
      TipsDialog.login(
        context,
        () {
          goPage(context, '/phoneLogin');
        },
      );
      return;
    }

    String url = list[index].adHref;
    if (url.contains('http') && await canLaunch(url)) {
      return launch(url);
    }
    if (list[index].adHref != null && list[index].adHref.length > 0) {
      return goPage(context, list[index].adHref);
    }
  }
}

/// 我的关注
class _MyFollowBuild extends StatefulWidget {
  _MyFollowBuild({Key key}) : super(key: key);

  @override
  __MyFollowBuildState createState() => __MyFollowBuildState();
}

class __MyFollowBuildState extends State<_MyFollowBuild> {
  List<FollowModel> list = [];

  @override
  void initState() {
    super.initState();
    UserApis.followMan().then((arr) {
      list = arr;
      setState(() {});
    });
  }

  @override
  Widget build(BuildContext context) {
    if (list.length >= 5) {
      list = list.sublist(0, 5);
    }
    return Container(
      height: px(150),
      padding: EdgeInsets.symmetric(horizontal: px(30)),
      margin: EdgeInsets.only(top: px(5)),
      child: Row(
        children: list.asMap().keys.map((i) {
          if (i == list.length - 1) {
            return anchor(list[i]);
          } else {
            return Container(
              margin: EdgeInsets.only(right: px(33)),
              child: anchor(list[i]),
            );
          }
        }).toList(),
      ),
    );
  }

  // 昵称
  Text nickName(sign) {
    return Text(
      sign,
      overflow: TextOverflow.ellipsis,
      style: TextStyle(
        color: col("303133"),
        fontSize: px(24),
      ),
    );
  }

  // 单个主播
  Widget anchor(FollowModel item) {
    return Container(
      width: px(110),
      child: Column(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: <Widget>[
          Avatar(
            item.memberHead,
            true,
            token: item.memberToken,
          ),
          nickName(item.memberNickname),
        ],
      ),
    );
  }
}

/// 热门主播
class _HotBuild extends StatelessWidget {
  const _HotBuild({Key key}) : super(key: key);

  // 生成热门直播
  Widget hotHandle(context, RecommendModel item) {
    return GestureDetector(
      onTap: () {
        final user = Provide.value<UserState>(context);
        final info = user.info;
        final isLogin = info != null;
        if (isLogin) {
          goPage(context, '/anchorInfo', param: {'token': item.memberToken});
        } else {
          TipsDialog.login(
            context,
            () {
              goPage(context, '/phoneLogin');
            },
          );
        }
      },
      child: Container(
        width: px(334),
        height: px(470),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: <Widget>[
            ClipRRect(
              borderRadius: BorderRadius.circular(px(10)),
              child: Stack(
                children: <Widget>[
                  Container(
                    width: px(334),
                    height: px(334),
                    child: CachedNetworkImage(
                      imageUrl: "${item.firstimg}?imageView2/2/w/334",
                      fit: BoxFit.cover,
                      errorWidget: (context, url, error) {
                        return Config.errorNetImage;
                      },
                    ),
                  ),
                  Positioned(
                    top: px(15),
                    right: px(15),
                    child: Container(
                      height: px(30),
                      padding: EdgeInsets.symmetric(horizontal: px(10)),
                      decoration: BoxDecoration(
                        borderRadius: BorderRadius.all(Radius.circular(px(15))),
                        color: Colors.black.withOpacity(.3),
                      ),
                      child: Row(
                        children: <Widget>[
                          Container(
                            width: px(8),
                            height: px(8),
                            margin: EdgeInsets.only(right: px(5)),
                            decoration: BoxDecoration(
                              color: CommonAction.checkAnchorStatus(
                                item.disturb,
                                item.online,
                              ).color,
                              borderRadius: BorderRadius.circular(
                                px(4),
                              ),
                            ),
                          ),
                          Text(
                            "${CommonAction.checkAnchorStatus(
                              item.disturb,
                              item.online,
                            ).text}",
                            style: TextStyle(
                              color: Colors.white,
                              fontSize: px(22),
                            ),
                          ),
                        ],
                      ),
                    ),
                  ),
                  // Positioned(
                  //   top: px(15),
                  //   right: px(15),
                  //   child: Container(
                  //     height: px(30),
                  //     padding: EdgeInsets.symmetric(horizontal: px(6)),
                  //     decoration: BoxDecoration(
                  //       borderRadius: BorderRadius.circular(px(4)),
                  //       gradient: LinearGradient(colors: [
                  //         col("2becdd"),
                  //         col("24d4f2"),
                  //         col("5a93fe"),
                  //       ]),
                  //     ),
                  //     child: Text(
                  //       "试看1分钟",
                  //       style: TextStyle(
                  //         color: Colors.white,
                  //         fontSize: px(20),
                  //       ),
                  //     ),
                  //   ),
                  // ),
                  Positioned(
                    bottom: px(15),
                    left: px(15),
                    child: Container(
                      child: Row(
                        children: <Widget>[
                          Container(
                            margin: EdgeInsets.only(right: px(7)),
                            child: Image.asset(
                              "assets/images/icon/money.png",
                              width: px(26),
                              height: px(26),
                            ),
                          ),
                          Text(
                            "${item.timePrice}金币/分钟",
                            style: TextStyle(
                              color: Colors.white,
                              fontSize: px(24),
                            ),
                          )
                        ],
                      ),
                    ),
                  )
                ],
              ),
            ),
            Container(
              margin: EdgeInsets.only(top: px(25)),
              child: Text(
                item.memberNickname,
                overflow: TextOverflow.ellipsis,
                style: TextStyle(
                  color: col("303133"),
                  fontSize: px(30),
                ),
              ),
            ),
            Container(
              margin: EdgeInsets.only(top: px(15)),
              child: Text(
                item.anchorSign,
                overflow: TextOverflow.ellipsis,
                style: TextStyle(
                  color: col("909399"),
                  fontSize: px(24),
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    final NominateBloc bloc = BlocProvider.of<NominateBloc>(context);
    return StreamBuilder<List<RecommendModel>>(
      stream: bloc.outRecommendList,
      initialData: [],
      builder: (
        BuildContext context,
        AsyncSnapshot<List<RecommendModel>> snapshot,
      ) {
        return Container(
          margin: EdgeInsets.only(top: px(15)),
          padding: EdgeInsets.symmetric(horizontal: px(30)),
          child: Wrap(
            spacing: px(21),
            runSpacing: px(36),
            children: snapshot.data.map<Widget>((f) {
              return hotHandle(context, f);
            }).toList(),
          ),
        );
      },
    );
  }
}
